//
//  WmcHomeVM+PhotoCombine.swift
//  YPWatermarkCamera
//
//  Created by Json on 2023/8/3.
//

import Foundation
import HandyJSON

extension WmcHomeVM {
    
    /// 修改拼图设置后调用
    func didChangedCombinePhotoSetting() {
        if let json = combinePhotoSetting.toJSONString() {
            WmcUserdefault.save(value: json, forKey: .State.CombinePhoto.setting)
        }
    }
    
    /// 拼图
    func asynCombinePhotos(completion: @escaping (() -> Void)) {
        transactionQueue.async {
            [weak self] in
            guard let self = self else { return }
            // 拼接图片
            let image = self.combinePhotos()
            YPGCD.Main {
                // 回调
                completion()
                // 保存并上传图片
                if let image = image {
                    self.saveCombined(photo: image)
                    WmcHudManager.toast("保存成功,可在本地相册查看")
                }
            }
        }
    }
    
    /// 拼接图片
    func combinePhotos() -> UIImage? {
        guard let firstImage = combinedPhotos.first else {
            WmcWarning("拼图==>获取图片失败")
            return nil
        }
        let imageW = firstImage.size.width
        let imageH = firstImage.size.height
        // 画布宽度
        var canvasW = imageW
        // 画布高度
        // 排放的列数
        let columns = combinePhotoSetting.columns.rawValue
        // 缩放比例
        let scale: CGFloat
        switch combinePhotoSetting.columns {
        case .one: // 单列
            scale = 2.0
            // 画布宽度
            canvasW = imageW / scale
        default: // 其他布局
            scale = columns.yp.cgFloat
        }
        // 排放的图片宽高
        let combineImageW = imageW / scale
        let combineImageH = imageH / scale
        // 图片总数
        let totalPhotoNum = combinedPhotos.count
        // 排放的总行数
        let rows = (totalPhotoNum - 1) / columns + 1
        // 标题高度
        let titleImage = "icon_work_report_984_180".wmc_image
        let titleW: CGFloat
        let titleH: CGFloat
        switch combinePhotoSetting.style {
        case .default:
            titleW = 0.0
            titleH = 0.0
        case .workReport:
            switch combinePhotoSetting.columns {
            case .one:
                titleW = combineImageW
            default:
                titleW = canvasW
            }
            titleH = titleW * titleImage.size.height / titleImage.size.width
        }
        // 画布高度
        let canvasH = combineImageH * rows.yp.cgFloat + titleH
        guard canvasW > 0 && canvasH > 0 else { return nil }
        UIGraphicsBeginImageContextWithOptions(CGSize(width: canvasW, height: canvasH), false, firstImage.scale)
        
        // 标题X坐标
        let titleX = 0.0
        // 标题Y坐标
        let titleY = 0.0
        // 绘制标题
        if titleH != 0.0 {
            titleImage.draw(in: CGRect(x: titleX, y: titleY, width: titleW, height: titleH))
        }
        
        // 绘制图片
        for (index, image) in combinedPhotos.enumerated() {
            // 行号
            let row = index / columns
            // 列号
            let column = index % columns
            // 画图
            let imageX = column.yp.cgFloat * combineImageW
            let imageY = row.yp.cgFloat * combineImageH + titleY + titleH
            image.draw(in: CGRect(x: imageX, y: imageY, width: combineImageW, height: combineImageH))
        }
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
    /// 存储并上传图片
    /// - Parameters:
    ///   - photo: 图片
    ///   - watermarkModel: 水印信息
    func saveCombined(photo: UIImage) {
        // 存入系统相册
        WmcAlbumManager.saveMyAlbumCollection(image: photo)
        let watermarkModel = lastWatermarkModel ?? .init()
        let noWatermarkInfo = WmcWatermarkDataTool.createNoneWatermark(addressModel: watermarkModel.staticData.drawStaticAddress, addressPrefix: watermarkModel.staticData.staticAddressPrefix)
        let noWatermarkModel = watermarkModel.copyModel() ?? .init()
        noWatermarkModel.wmId = 0
        // 存储数据库
        WmcLocalMediaAlbumDBManager.insertImage(.init(uiImage: photo), watermarkJson: noWatermarkInfo.json) {
            [weak self]
            originMediaType, // 媒体类型
                originPreviewImagePath, // 预览图完整路径
                originPreviewImageRelativePath, // 预览图相对路径
                originMediaInfoModel // 媒体对象
            in
            guard let self = self else { return }
            self.syncLocalAlbumList() // 同步下数据库
            // 上传
            self.isLoginWithNewUser { isLogin in
                if !isLogin { return }
                self.uploadImage(imagePath: originMediaInfoModel.relativePath,
                                 watermarkModel: noWatermarkModel,
                                 watermarkInfo: noWatermarkInfo.dict,
                                 previewImagePath: originPreviewImageRelativePath,
                                 standardPhoto: photo)
            }
        }
    }
}
